package com.hzy.orderSystem.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzy.orderSystem.dao.OrderDao;
import com.hzy.orderSystem.entities.Order;
import com.hzy.orderSystem.entities.Record;
import com.hzy.orderSystem.entities.Support;
import com.hzy.orderSystem.service.OrderService;
import com.hzy.orderSystem.service.RecordService;
import com.hzy.orderSystem.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 小宝
 * @create 2021/4/17 11:39
 */
@RestController
@RequestMapping("/record")
public class RecordController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RecordService recordService;
    @Autowired
    OrderService orderService;

    /**
     * 继续提出问题或者回答问题
     * @param map oid: 工单id
     *            content: 问题或者回答
     * @param request
     * @return
     */
    @PostMapping("/add")
    public CommonResult addRecord(@RequestBody Map<String, String> map,
                                  HttpServletRequest request){
        String token = request.getHeader("X-Token");
        Long oid = Long.parseLong(map.get("oid"));
        String content = map.get("content");
        String message = "提问成功";

        Object obj = redisTemplate.opsForValue().get(token);
        if(obj == null)
            return new CommonResult(40000, "登录已失效，请重新登录");
        Map<String, String> objMap = JSON.parseObject(
                JSONObject.toJSONString(obj), Map.class
        );
        String role = objMap.get("role");
        String username = objMap.get("username");

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Order order = new Order(oid, 0, sdf.format(date));
        Record record = new Record(content, sdf.format(date), 0, order);
        if(role.equals("support")){
            record.setType(1);
            record.setSupport((Support) obj);
            message = "回答成功";
            order.setStatus(1);
            order.setSupport((Support) obj);
        }
        int save = recordService.save(record);
        int update = orderService.updateOrder(order);
        if(save > 0 && update > 0){
            JSONObject data = new JSONObject();
            data.put("content", record.getContent());
            data.put("type", record.getType());
            data.put("time", record.getTime());
            data.put("username", username);
            return new CommonResult(20000, message, data);
        }
        else
            return new CommonResult(40000, "提交失败");
    }

}
